<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="商品分类" prop="classifyName">
        <el-select
          v-model="queryParams.classifyId"
          placeholder="请选择所属分类"
          clearable
          size="small"
        >
          <el-option
            :key="classify.classifyId"
            :label="classify.classifyName"
            :value="classify.classifyId"
            v-for="classify in goodsClassifyListForOne"
          >{{ classify.classifyName }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          ref="input"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择商品状态"
          clearable
          size="small"
        >
          <el-option label="下架" value="10" />
          <el-option label="上架" value="20" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:goods:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:goods:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:goods:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:goods:export']"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="goodsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="expand" label="详情" v-if="isExpand">
        <template slot-scope="scope">
          <el-table
            :data="scope.row.goodsKeepList"
            border
            :summary-method="getSummaries"
            show-summary
            :header-cell-style="headClass"
          >
            <el-table-column label="库存ID" align="center" prop="keepId" />
            <el-table-column label="店铺名称" align="center" prop="goodsName" />
            <el-table-column
              label="商品价格"
              align="center"
              prop="goodsPrice"
            />
            <el-table-column
              label="拼团价格"
              align="center"
              prop="groupPrice"
            />
            <el-table-column label="划线价格" align="center" prop="linePrice">
              <template
                slot-scope="scope"
                v-if="scope.row.linePrice != undefined"
              >
                <s>{{ scope.row.linePrice }}</s>
              </template>
            </el-table-column>
            <el-table-column label="商品状态" align="center" prop="status">
              <template slot-scope="scope">
                <el-tag type="warning" v-if="scope.row.status == 10"
                >禁用</el-tag
                >
                <el-tag type="success" v-if="scope.row.status == 20"
                >启用</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="库存" align="center" prop="keepNum">
            </el-table-column>
            <el-table-column label="销量" align="center" prop="saleNum" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="goodsId" />
      <el-table-column
        label="序号"
        type="index"
        align="center"
        :index="indexMethod"
        width="50px"
      />
      <el-table-column label="ID" align="center" prop="goodsId" />
      <el-table-column label="所属分类" align="center" prop="classifyName" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="商品主图" align="center" prop="goodsImg">
        <template slot-scope="scope" v-if="scope.row.goodsImg != null">
          <el-image
            :preview-src-list="scope.row.goodsImg.split(',')"
            style="width: 30px; height: 30px"
            shape="square"
            :src="image"
            :key="image"
            v-for="image in scope.row.goodsImg.split(',')"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品价格" align="center" prop="goodsPrice" />
      <el-table-column label="拼团价格" align="center" prop="groupPrice" />
      <el-table-column label="会员价格" align="center" prop="vipPrice" />
      <el-table-column label="划线价格" align="center" prop="linePrice">
        <template slot-scope="scope" v-if="scope.row.linePrice != undefined">
          {{ scope.row.linePrice }}
        </template>
      </el-table-column>
      <el-table-column label="属性" align="center" prop="attributes" />
      <el-table-column label="属性名" align="center" prop="attributesName" />
      <el-table-column label="提成比" align="center" prop="percent" />
      <el-table-column label="商品状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.status == 10">下架</el-tag>
          <el-tag type="success" v-if="scope.row.status == 20">上架</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="商品标签"
        align="center"
        prop="goodsMark"
        :formatter="goodsLableFormat"
      />
      <el-table-column label="商品所属" align="center" prop="addType">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.addType == 10">平台</el-tag>
          <el-tag type="info" v-if="scope.row.addType == 20">商家</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="预售时间"
        align="center"
        prop="startDate"
        width="180"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="280"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['system:goods:keep']"
            @click="handleSkuUpdate(scope.row)"
          >
            库存配置
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleChangeState(scope.row)"
            v-if="scope.row.status == '10'"
            v-hasPermi="['system:goods:changeState']"
          >上架
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleChangeState(scope.row)"
            v-if="scope.row.status == '20'"
            v-hasPermi="['system:goods:changeState']"
          >下架
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:goods:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:goods:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改商品信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--基础信息-->
        <el-row justify="start" style="display: flex">
          <el-form-item label="所属分类" prop="classifyId">
            <el-select
              v-model="form.classifyId"
              placeholder="请选择所属分类"
              clearable
              size="small"
            >
              <el-option
                :key="classify.classifyId"
                :label="classify.classifyName"
                :value="classify.classifyId"
                v-for="classify in goodsClassifyList"
              >{{ classify.classifyName }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品标签">
            <el-select
              v-model="form.goodsMark"
              multiple
              placeholder="请选择商品标签"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in goodsLableList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="排序编号" prop="sort">
            <el-input v-model="form.sort" placeholder="请输入商品排序号" />
          </el-form-item>
        </el-row>
        <el-row justify="start" style="display: flex">
          <el-form-item label="商品状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio label="10">下架</el-radio>
              <el-radio label="20">上架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="推荐置顶" prop="top" style="margin-right:30px;">
            <el-radio-group v-model="form.top">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="优惠比" prop="proportion">
            <el-input
              v-model="form.proportion"
              placeholder="请输入商品优惠百分比"
              size="small"
            /><em>(例如 '10%')</em>
          </el-form-item>
          <el-form-item label="提成比" prop="proportion">
            <el-input
              v-model="form.percent"
              placeholder="请输入商品提成百分比"
              size="small"
            /><em>(例如 '10%')</em>
          </el-form-item>
        </el-row>
        <el-row justify="start" style="display: flex">
          <el-form-item label="平台保障" prop="guarantee">
            <el-input
              v-model="form.guarantee"
              placeholder="请输入平台保障"
              size="small"
            /><em>(例如 '无忧退换')</em>
          </el-form-item>
          <el-form-item label="推荐用语" prop="supplierDesc">
            <el-input
              v-model="form.supplierDesc"
              placeholder="请输入推荐用语"
              size="small"
            /><em>(例如 '力荐')</em>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="start">
          <el-form-item
            label="预售时间"
            prop="startDate"
            :rules="{
              required: true,
              message: '预售时间不能为空',
              trigger: ['blur', 'change'],
            }"
          >
            <el-date-picker
              v-model="form.startDate"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              :picker-options="startDateLimit"
              value-format="timestamp"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="提货时间"
            prop="pickDate"
            :rules="{
              required: true,
              message: '提货时间不能为空',
              trigger: ['blur', 'change'],
            }"
          >
            <el-date-picker
              disabled
              v-model="form.pickDate"
              format="yyyy-MM-dd HH:mm"
              value-format="timestamp"
              type="datetime"
              :picker-options="startDateLimit"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="start">
          <el-form-item
            label="人气值"
            prop="popularity"
            :rules="{
              required: true,
              message: '基础人气值不能为空',
              trigger: ['blur', 'change'],
            }"
          >
            <el-input-number
              v-model="form.popularity"
              :min="0"
              :step="1"
              size="small"
            />
          </el-form-item>
          <el-form-item
            label="规格"
            prop="spec"
            :rules="{
              required: true,
              message: '规格不能为空',
              trigger: ['blur', 'change'],
            }"
          >
            <el-select
              v-model="form.spec"
              placeholder="请选择规格"
              clearable
              size="small"
            >
              <el-option
                :key="unit"
                :label="unit"
                :value="unit"
                v-for="unit in unitArr"
              >{{ unit }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="起售份数"
            prop="lowNum"
            :rules="{
              required: true,
              message: '最低起售数量不能为空',
              trigger: ['blur', 'change'],
            }"
          >
            <el-input-number
              v-model="form.lowNum"
              :min="1"
              :step="1"
              size="small"
            />
          </el-form-item>
        </el-row>
        <el-row
          class="customWidth"
          style="
            margin-bottom: 30px;
            background: #ecf8ff;
            padding: 30px 30px 0 30px;
          "
          v-for="(attrItem, index) in form.attrRows"
          :key="index"
        >
          <el-col>
            <el-row type="flex" justify="start">
              <el-form-item
                label="商品名称"
                :prop="'attrRows.' + index + '.goodsName'"
                :rules="{
                  required: true,
                  message: '属性不能为空',
                  trigger: ['blur', 'change'],
                }"
              >
                <el-input
                  v-model="attrItem.goodsName"
                  placeholder="请输入商品名称"
                />
              </el-form-item>
              <el-form-item
                label="属性"
                :prop="'attrRows.' + index + '.attributes'"
                :rules="{
                  required: true,
                  message: '属性不能为空',
                  trigger: ['blur', 'change'],
                }"
              >
                <el-input
                  v-model="attrItem.attributes"
                  placeholder="请输入商品属性"
                />
              </el-form-item>
            </el-row>
            <el-row type="flex" justify="start">
              <el-form-item
                label="划线价格"
                :prop="'attrRows.' + index + '.linePrice'"
                :rules="{
                  required: true,
                  message: '划线价格不能为空',
                  trigger: ['blur', 'change'],
                }"
              >
                <el-input-number
                  v-model="attrItem.linePrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                />
              </el-form-item>
              <el-form-item
                label="拼团价格"
                :prop="'attrRows.' + index + '.groupPrice'"
                :rules="{
                  required: true,
                  message: '拼团价格不能为空',
                  trigger: ['blur', 'change'],
                }"
              >
                <el-input-number
                  v-model="attrItem.groupPrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                />
              </el-form-item>
              <el-form-item
                label="进货价"
                :prop="'attrRows.' + index + '.buyPrice'"
                :rules="{
                  required: true,
                  message: '进货价格不能为空',
                  trigger: ['blur', 'change'],
                }"
              >
                <el-input-number
                  v-model="attrItem.buyPrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                />
              </el-form-item>
            </el-row>
          </el-col>
          <el-col>
            <el-row type="flex" justify="start">
              <el-form-item
                label="会员价格"
                :prop="'attrRows.' + index + '.vipPrice'"
                :rules="{
                  required: true,
                  message: '会员价格不能为空',
                  trigger: ['blur', 'change'],
                }"
              >
                <el-input-number
                  v-model="attrItem.vipPrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                />
              </el-form-item>
            </el-row>
          </el-col>
          <el-col>
            <el-form-item
              label="商品主图"
              :prop="'attrRows.' + index + '.goodsMainImgs'"
              :rules="{
                required: true,
                message: '列表图片不能为空',
                trigger: 'blur',
              }"
            >
              <el-upload
                :action="commonUploadApi"
                :accept="'.png,.jpg'"
                :show-file-list="true"
                :multiple="true"
                :limit="7"
                list-type="picture-card"
                :file-list="attrItem.goodsMainImgs"
                :class="{
                  hideUpload:
                    attrItem.goodsMainImgs &&
                    attrItem.goodsMainImgs.length >= 7,
                }"
                :headers="headers"
                :on-success="
                  (response, file, fileslist) => {
                    handleUploadGoodsMainImgs(response, file, fileslist, index);
                  }
                "
                :on-exceed="() => handleExceedGoodsMainImgs(7)"
                :on-remove="
                  (file, fileslist) => {
                    handleRemoveGoodsMainImgs(file, fileslist, index);
                  }
                "
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>

            <el-form-item
              label="商品宽图"
              :prop="'attrRows.' + index + '.goodsLongImgs'"
              :rules="{
                required: true,
                message: '列表图片不能为空',
                trigger: 'blur',
              }"
            >
              <el-upload
                :action="commonUploadApi"
                :accept="'.png,.jpg'"
                :show-file-list="true"
                :multiple="true"
                :limit="7"
                list-type="picture-card"
                :file-list="attrItem.goodsLongImgs"
                :class="{
                  hideUpload:
                    attrItem.goodsLongImgs &&
                    attrItem.goodsLongImgs.length >= 7,
                }"
                :headers="headers"
                :on-success="
                  (response, file, fileslist) => {
                    handleUploadGoodsLongImgs(response, file, fileslist, index);
                  }
                "
                :on-exceed="() => handleExceedGoodsLongImgs(7)"
                :on-remove="
                  (file, fileslist) => {
                    handleRemoveGoodsLongImgs(file, fileslist, index);
                  }
                "
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品图集" prop="listImg">
          <el-upload
            :action="commonUploadApi"
            :accept="'.png,.jpg'"
            :show-file-list="true"
            :multiple="true"
            :limit="7"
            list-type="picture-card"
            :file-list="form.listImg"
            :class="{ hideUpload: form.listImg && form.listImg.length >= 7 }"
            :headers="headers"
            :on-success="handleUploadListImg"
            :on-exceed="() => handleExceedListImg(7)"
            :on-remove="handleRemoveListImg"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品视频" prop="goodsVideo">
          <el-upload
            ref="goodsVideoUpload"
            :action="commonUploadApi"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleVideoRemove"
            :on-success="uploadVideoSuccess"
            :headers="headers"
            :limit="1"
          >
            <video
              v-if="form.goodsVideo"
              style="width: 200px; height: 200px"
              v-bind:src="form.goodsVideo"
              class="avatar video-avatar"
              controls="controls"
            >
              您的浏览器不支持视频播放
            </video>
            <el-button
              v-if="!form.goodsVideo"
              slot="trigger"
              size="small"
              type="primary"
            >选取文件</el-button
            >
          </el-upload>
          <el-button
            v-if="form.goodsVideo"
            @click.native="handleVideoRemove"
            size="small"
            type="primary"
          >删除文件</el-button
          >
        </el-form-item>
        <el-form-item label="商品内容" prop="goodsContent">
          <Editor v-model="form.goodsContent" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改商品库存信息对话框 -->
    <el-dialog
      title="库存配置"
      :visible.sync="openSku"
      width="500px"
      append-to-body
    >
      <el-form
        ref="skuForm"
        :model="skuForm"
        :rules="skuRules"
        label-width="80px"
      >
        <el-form-item label="库存" prop="keepNum">
          <el-input v-model="skuForm.keepNum" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="销量" prop="saleNum">
          <el-input-number v-model="skuForm.saleNum" :min="0" :step="1" />
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input-number
            v-model="skuForm.goodsPrice"
            :min="0"
            :precision="2"
            :step="0.1"
          />
        </el-form-item>
        <el-form-item label="划线价格" prop="linePrice">
          <el-input-number
            v-model="skuForm.linePrice"
            :min="0"
            :precision="2"
            :step="0.1"
          />
        </el-form-item>
        <el-form-item label="拼团价格" prop="groupPrice">
          <el-input-number
            v-model="skuForm.groupPrice"
            :min="0"
            :precision="2"
            :step="0.1"
          />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="skuForm.status">
            <el-radio label="10">下架</el-radio>
            <el-radio label="20">上架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSkuForm">确 定</el-button>
        <el-button @click="skuCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getGoods as getSingleGoods, delGoods as delSingleGoods } from "@/api/system/goods";
  import {
    listGoods,
    getGoods,
    delGoods,
    addGoods,
    updateGoods,
    exportGoods,
    changeState,
    getKeepGoods,
    transformnNormalGoods
  } from "@/api/system/preSale";
  import { addKeep, updateKeep } from "@/api/system/keep";
  import { mapGetters } from "vuex";
  import { getToken } from "@/utils/auth";
  import Editor from "@/components/Editor";
  import {
    getGoodsClassify,
    getGoodsClassifyListForOne,
  } from "@/api/system/classify";
  import store from "@/store";
  import { remove } from "@/api/tool/file";

  export default {
    name: "Goods",
    components: {
      Editor,
    },
    data() {
      return {
        startDateLimit: {
          disabledDate: (time) => {
            return time.getTime() < Date.now() - 8.64e7;
          },
        },
        // exportSkuIndex
        exportSkuIndex: "",

        unitArr: ["斤", "个", "颗", "克", "吨", "袋", "位", "提", "包"],
        //
        isExpand: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        //商品标签
        goodsLableList: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 商品信息表格数据
        goodsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        openSku: false,
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++查看图集操作
        dialogImageUrl: "",
        dialogVisible: false,
        // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          classifyId: undefined,
          goodsContent: undefined,
          goodsType: "50",
          listImg: undefined,
          goodsPrice: undefined,
          linePrice: undefined,
          groupPrice: undefined,
          goodsMark: undefined,
          status: undefined,
          addType: undefined,
          attributes: undefined,
          attributesName: undefined,
          mainCategory: undefined,
          shopId: undefined,
          delFalg: undefined,
        },
        headers: { Authorization: "Bearer " + getToken() },
        // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++表单参数
        form: {},
        skuForm: {},
        //商品分类集合
        goodsClassifyListForOne: [],
        goodsClassifyList: [],
        // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++表单校验
        rules: {
          classifyId: [
            { required: true, message: "所属分类不能为空", trigger: "blur" },
          ],
          goodsName: [
            { required: true, message: "商品名称不能为空", trigger: "blur" },
          ],
          attributes: [
            { required: true, message: "商品属性不能为空", trigger: "blur" },
          ],
          attributesName: [
            { required: true, message: "商品属性名不能为空", trigger: "blur" },
          ],
          mainCategory: [
            { required: true, message: "商品主类别不能为空", trigger: "blur" },
          ],
          goodsImg: [
            { required: true, message: "商品图片不能为空", trigger: "blur" },
          ],
          goodsLongImg: [
            { required: true, message: "商品宽图不能为空", trigger: "blur" },
          ],
          listImg: [
            { required: true, message: "列表图片不能为空", trigger: "blur" },
          ],
          status: [
            { required: true, message: "请选择商品状态", trigger: "blur" },
          ],
          goodsContent: [
            { required: true, message: "请输入商品内容", trigger: "blur" },
          ],
        },
        skuRules: {
          keepNum: [{ required: true, message: "库存不能为空", trigger: "blur" }],
          saleNum: [{ required: true, message: "销量不能为空", trigger: "blur" }],
          goodsPrice: [
            { required: true, message: "商品价格不能为空", trigger: "blur" },
          ],
          linePrice: [
            { required: true, message: "划线价格不能为空", trigger: "blur" },
          ],
          groupPrice: [
            { required: true, message: "拼团价格不能为空", trigger: "blur" },
          ],
          status: [
            { required: true, message: "商品状态不能为空", trigger: "blur" },
          ],
        },
      };
    },
    computed: {
      ...mapGetters(["commonUploadApi"]),
    },
    watch: {
      'form.startDate'(newval) {
        const d = new Date(newval)
        d.setDate(d.getDate() + 1)
        d.setHours(16)
        d.setMinutes(0)
        d.setSeconds(0)
        this.form.pickDate = d
      },
      '$route'(newval) {
        if(newval.name == 'PreSale') {
          this.transformGoods()
        }
      }
    },
    created() {
      console.log('111111')
      this.changeFocus();
      const roles = store.getters && store.getters.roles;
      if (roles.indexOf("admin") > -1) {
        this.isExpand = true;
      }
      this.getList();
      getGoodsClassifyListForOne().then((response) => {
        this.goodsClassifyListForOne = response.data;
      });
      getGoodsClassify().then((response) => {
        this.goodsClassifyList = response.data;
      });
      this.getDicts("goods_mark").then((response) => {
        this.goodsLableList = response.data;
      });
    },
    mounted() {
      this.transformGoods()
    },
    methods: {
      // 转预售
      transformGoods() {
        let query = this.$route.query || {}
        if(query.isTransform && query.id) {
          getSingleGoods(query.id).then((res) => {
            this.reset()
            let form = {
              ...this.form,
              ...res.data,
              goodsType: 50
            };

            // let form = new Object()
            // for(let i in this.form) {
            //   form[i] = res.data[i]
            // }
            // form.goodsId = undefined
            // form.goodsType = 50


            if (form.goodsMark != null) {
              form.goodsMark = form.goodsMark.split(",");
            }

            //处理图片
            //图片回显
            let attrRows = form.attrRows.map((item) => {
              return {
                ...item,
                goodsMainImgs: this.strToArr(item.goodsMainImgs || ""),
                goodsLongImgs: this.strToArr(item.goodsLongImgs || ""),
              };
            });
            let listImg = this.strToArr(form.listImg || "");
            this.form = {
              ...form,
              listImg,
              attrRows,
            };

            this.open = true;
            this.title = "新增商品信息";
          })
        }
      },
      // 删除属性
      removeAttribute(index) {
        let arr = [...this.form.attrRows];
        arr.splice(index, 1);
        this.form.attrRows = arr;
      },
      // 添加属性
      addAttributes() {
        this.form.attrRows.push({
          attributes: undefined,
          goodsPrice: 0,
          linePrice: 0,
          groupPrice: 0,
          buyPrice: 0,
          goodsName: undefined,
          goodsImg: undefined,
          goodsLongImg: undefined,
          goodsMainImgs: undefined,
          goodsLongImgs: undefined,
        });
      },
      //改变焦点
      changeFocus() {
        this.$nextTick((x) => {
          this.$refs.input.focus();
        });
      },

      //商户更改商品状态
      handleChangeState(row) {
        let str = "下架";
        if (row.status == "10") {
          str = "上架";
        }
        this.$confirm("是否确认" + str + "选择的商品?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return changeState(row);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("已" + str);
          })
          .catch(function () {});
      },
      goodsLableFormat(row, column) {
        let strArray = [];
        let markArray = row.goodsMark.split(",");
        for (let i = 0; i < markArray.length; i++) {
          strArray.push(this.selectDictLabel(this.goodsLableList, markArray[i]));
        }
        return strArray.join(",");
      },
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 4) {
            sums[index] = "总计:";
            return;
          }
          const values = data.map((item) => Number(item[column.property]));
          if (index == 5 || index == 6) {
            if (!values.every((value) => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              if (index == 5) {
                sums[5] += " (当前)";
              } else if (index == 6) {
                sums[6] += " (已售)";
              }
            }
          }
        });
        return sums;
      },
      //+++++++++++++++++++++++++++++++++++++上传商品主图操作
      // handleSuccessGoodsImage(response, file, fileList, index) {
      //   let data = [...this.form.attrRows]
      //   data[index].goodsImg = response.url;
      //   this.form.attrRows = [...data]
      // },
      // 主图集合
      handleUploadGoodsMainImgs(response, file, filelist, index) {
        let data = [...this.form.attrRows];
        if (filelist[0].status == "success") {
          data[index].goodsImg = filelist[0] && filelist[0].response.url || '';
        }
        data[index].goodsMainImgs = this.uploadChangeUrl(filelist);
        this.form.attrRows = [...data];
      },
      handleRemoveGoodsMainImgs(file, filelist, index) {
        let data = [...this.form.attrRows];
        data[index].goodsImg = filelist[0] && filelist[0].response.url || '';
        data[index].goodsMainImgs = this.uploadChangeUrl(filelist);
        this.form.attrRows = [...data];
      },
      handleExceedGoodsMainImgs(limit) {
        this.msgError(`不能超过${limit}张`);
        return false;
      },
      // 长图集合
      handleUploadGoodsLongImgs(response, file, filelist, index) {
        let data = [...this.form.attrRows];
        if (filelist[0].status == "success") {
          data[index].goodsLongImg = filelist[0] && filelist[0].response.url || '';
        }
        data[index].goodsLongImgs = this.uploadChangeUrl(filelist);
        this.form.attrRows = [...data];
      },
      handleRemoveGoodsLongImgs(file, filelist, index) {
        let data = [...this.form.attrRows];
        data[index].goodsLongImg = filelist[0] && filelist[0].response.url || '';
        data[index].goodsLongImgs = this.uploadChangeUrl(filelist);
        this.form.attrRows = [...data];
      },
      handleExceedGoodsLongImgs(limit) {
        this.msgError(`不能超过${limit}张`);
        return false;
      },
      // 商品图集
      handleUploadListImg(response, file, filelist) {
        this.form.listImg = this.uploadChangeUrl(filelist);
      },
      handleRemoveListImg(file, filelist) {
        this.form.listImg = this.uploadChangeUrl(filelist);
      },
      handleExceedListImg(limit) {
        this.msgError(`不能超过${limit}张`);
        return false;
      },

      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleVideoRemove() {
        this.$refs.goodsVideoUpload.clearFiles();
        remove(this.form.goodsVideo).then((response) => {
          if (response.data.code == "200") {
            this.msgSuccess("删除成功");
          } else {
            this.msgError("删除失败");
          }
        });
        this.form = {
          ...this.form,
          goodsVideo: "",
        };
      },
      uploadVideoSuccess(response, file, fileList) {
        this.form = {
          ...this.form,
          goodsVideo: response.url,
        };
      },
      /** 查询商品信息列表 */
      getList() {
        this.loading = true;
        listGoods(this.queryParams).then((response) => {
          this.goodsList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      skuCancel() {
        this.openSku = false;
        this.skuReset();
      },
      skuReset() {
        this.skuForm = {
          keepId: undefined,
          goodsId: undefined,
          keepNum: undefined,
          saleNum: "0",
          goodsPrice: undefined,
          linePrice: undefined,
          groupPrice: undefined,
          status: "20",
          goodsMark: undefined,
          delFalg: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
        };
        this.resetForm("skuForm");
      },
      // 表单重置
      reset() {
        this.form = {
          goodsVideo: undefined,
          goodsId: undefined,
          classifyId: undefined,
          goodsName: undefined,
          goodsImg: undefined,
          goodsLongImg: undefined,
          goodsContent: undefined,
          goodsType: "50",
          listImg: new Array(),
          goodsMark: undefined,
          status: "20",
          addType: undefined,
          shopId: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFalg: undefined,
          startDate: "",
          pickDate: "",
          popularity: "",
          spec: "",
          lowNum: "",
          attrRows: [
            // {
            // attributes: undefined,
            // goodsPrice: 0,
            // linePrice: 0,
            // groupPrice: 0,
            // goodsName: undefined,
            // goodsImg: undefined,
            // goodsMainImgs: [],
            // goodsLongImgs: [],
            // }
          ],
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.goodsId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.addAttributes();
        this.open = true;
        this.title = "添加商品信息";
      },
      handleSkuUpdate(row) {
        this.skuReset();
        const goodsId = row.goodsId || this.ids;
        getKeepGoods(goodsId).then((response) => {
          if (response.data != null) {
            this.skuForm = response.data;
          }
          this.skuForm.goodsId = goodsId;
          this.skuForm.goodsPrice = row.goodsPrice;
          this.skuForm.linePrice = row.linePrice;
          this.skuForm.groupPrice = row.groupPrice;
          //处理图片
          this.openSku = true;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const goodsId = row.goodsId || this.ids;
        getGoods(goodsId).then((response) => {
          let form = {
            ...this.form,
            ...response.data,
          };

          if (form.goodsMark != null) {
            form.goodsMark = form.goodsMark.split(",");
          }

          //处理图片
          //图片回显
          let attrRows = form.attrRows.map((item) => {
            return {
              ...item,
              goodsMainImgs: this.strToArr(item.goodsMainImgs || ""),
              goodsLongImgs: this.strToArr(item.goodsLongImgs || ""),
            };
          });
          let listImg = this.strToArr(form.listImg || "");
          this.form = {
            ...form,
            listImg,
            attrRows,
          };

          this.open = true;
          this.title = "修改商品信息";
        });
      },
      submitSkuForm: function () {
        this.$refs["skuForm"].validate((valid) => {
          if (valid) {
            if (this.skuForm.keepId != undefined) {
              updateKeep(this.skuForm).then((response) => {
                this.msgSuccess("修改成功");
                this.openSku = false;
                this.getList();
              });
            } else {
              addKeep(this.skuForm).then((response) => {
                this.msgSuccess("新增成功");
                this.openSku = false;
                this.getList();
              });
            }
          }
        });
      },
      uploadChangeUrl(filelist) {
        let arr = [...filelist];
        return arr.map((item) => {
          if (item.status == "success") {
            return {
              ...item,
              url: item.response.url,
            };
          } else {
            return null;
          }
        });
      },

      arrToStr(arr) {
        if (arr.length <= 0) return "";
        return arr
          .map((item) => {
            return item.response.url;
          })
          .join(",");
      },
      strToArr(str) {
        if (str == "") return [];
        return str.split(",").map((item) => {
          return {
            url: item,
            response: {
              url: item,
            },
          };
        });
      },
      /** 提交按钮 */
      submitForm() {
        let _this = this;
        this.$refs["form"].validate((valid) => {
          if (valid) {
            let attrRows = _this.form.attrRows.map((item) => {
              return {
                ...item,
                goodsMainImgs: _this.arrToStr(item.goodsMainImgs || []),
                goodsLongImgs: _this.arrToStr(item.goodsLongImgs || []),
              };
            });
            let form = {
              ..._this.form,
              listImg: _this.arrToStr(_this.form.listImg || []),
              attrRows: [...attrRows],
            };
            form.goodsMark =
              form.goodsMark instanceof Array
                ? form.goodsMark.join(",")
                : form.goodsMark;





            let query = this.$route.query || {}
            if(query.isTransform && query.id) {
              transformnNormalGoods(form).then(() => {
                _this.msgSuccess("新增成功");
                _this.open = false;
                _this.getList();
                _this.$router.push({
                  path: '/goods/preSale'
                })
                window.localStorage.setItem('refresh', JSON.stringify({
                  path: '/goods/goods',
                  value: true
                }))
              });
            } else {
              if (form.goodsId != undefined) {
                console.log(JSON.stringify(form));
                updateGoods(form).then((response) => {
                  _this.msgSuccess("修改成功");
                  _this.open = false;
                  _this.getList();
                });
              } else {
                addGoods(form).then((response) => {
                  _this.msgSuccess("新增成功");
                  _this.open = false;
                  _this.getList();
                });
              }
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const goodsIds = row.goodsId || this.ids;
        this.$confirm(
          '是否确认删除商品信息编号为"' + goodsIds + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return delGoods(goodsIds);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(function () {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm("是否确认导出所有商品信息数据项?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return exportGoods(queryParams);
          })
          .then((response) => {
            this.download(response.data);
          })
          .catch(function () {});
      },
      headClass() {
        return "text-align: center;background:#eef1f6;";
      },

      /** 序号*/
      indexMethod(index) {
        return (
          index + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
        );
      },
    },
  };
</script>
<style scoped>
  /*上传图片*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 70px;
    height: 70px;
    line-height: 70px;
    text-align: center;
    border: 1px solid #c0ccda;
  }

  .avatar {
    width: 70px;
    height: 70px;
    display: block;
  }

  /*动态标签*/
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .el-table th > .SkuClass {
    border: 1px solid red;
    background-color: red;
  }

  .customWidth /deep/ .el-input-number {
    width: 140px !important;
  }

  .hideUpload /deep/ .el-upload {
    display: none;
  }
</style>
